package com.fxu.framework.biz.aop;

import cn.hutool.core.util.StrUtil;
import com.fxu.framework.biz.ano.RedisLock;
import com.fxu.framework.core.exception.MsgException;
import com.fxu.framework.core.lock.LockHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

import static com.fxu.framework.biz.aop.LoggerAspect.getArgs;
import static com.fxu.framework.biz.aop.LoggerAspect.getStackTrace;

/**
 * 使用Redis全局锁
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
@Aspect
@Component
public class RedisLockAspect {
    @Pointcut("@annotation(com.fxu.framework.biz.ano.RedisLock)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLock redisLock = method.getAnnotation(RedisLock.class);
        Object[] args = joinPoint.getArgs();
        String redisKey = redisLock.prefix();
        if (StrUtil.isEmpty(redisKey)) redisKey = signature.getDeclaringType() + "." + method.getName();
        // 以第一个参数为KEY基础
        String fnlKey = redisKey + ":" + (args == null || args.length == 0 ? "" : String.valueOf(args[0]));
        return LockHolder.getLockHolder().lock(fnlKey, redisLock.second(), () -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable e) {
                log.info("RedisLock error! {}.{}({}), key={}, e={}", signature.getDeclaringType(),
                        method.getName(), getArgs(args), fnlKey, getStackTrace(e));
                throw new MsgException(e.getMessage());
            }
        });
    }

    // 配置异常通知
    @AfterThrowing(pointcut = "pointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        log.info("RedisLock error! {}.{}({}), e={}", signature.getDeclaringType(), method.getName(),
                getArgs(joinPoint.getArgs()), getStackTrace(e));
    }
}
